package com.example.tests;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.example.data.ContactData;
import com.thoughtworks.xstream.XStream;

public class ContactDataGenerator {

	public static void main(String[] args) throws IOException {
		if (args.length != 2) {
			System.out.println("Please specify parametres: <amount of test data> <file>");
			return;
		}
		
		int amount = Integer.parseInt(args[0]);
		File file = new File(args[1]);		
		
		if (file.exists()){
			System.out.println("File exists, please remote it manually: " + file);
			return;
		}
		
		saveContactsToXmlFile(generateRandomContacts(amount), file);		
		
	}

	private static void saveContactsToXmlFile(List<ContactData> contacts, File file) throws IOException {
			XStream xstream = new XStream();
			xstream.alias("contact", ContactData.class);
			String xml = xstream.toXML(contacts);
			FileWriter writer= new FileWriter(file);
			writer.write(xml);
			writer.close();			
	}
		
	public static List<ContactData> loadContactsFromXmlFile(File file) throws IOException {			
		XStream xstream = new XStream();
		xstream.alias("contact", ContactData.class);
		return (List<ContactData>) xstream.fromXML(file);
	}


	public static List<ContactData> generateRandomContacts(int amount) {
		 List<ContactData> list = new ArrayList<ContactData>();
		  for (int i = 0; i < amount; i++){
			   ContactData contact = new ContactData()
			   	.withFirstName(generateRandomString())
		    	.withLastName(generateRandomString())
		    	.withAddress(generateRandomString())
		    	.withHome(generateRandomString())
		    	.withMobile(generateRandomString())
		    	.withWork(generateRandomString())
		    	.withEmail(generateRandomString())
		    	.withEmail2(generateRandomString())
		    	.withBirthDay("3")
		    	.withBirthdayMonth("January")
		    	.withBirthdayYear("1989")
		    	.withAddress2(generateRandomString())
		    	.withPhone2(generateRandomString());				   			  
			   list.add(contact);
		  }
		  return list;
	}
	
	private static String generateRandomString(){
		  Random rnd = new Random();
		  if (rnd.nextInt(3) == 0) {
			   return "";
		   } else {
			   return "test" + rnd.nextInt();
		   }
	}	

}
